<template>
	<div class="system-role-dialog-container energy-from energy-dialog energy-table energy-tree">
		<el-dialog center align-center v-model="state.dialog.isShowDialog" width="60%" @close="resetData">
			<template #header="{ titleClass }">
				<div :class="titleClass">{{ state.dialog.isDetail ? '查看详情' : '绑定套餐' }}</div>
			</template>
			<el-tabs v-model="state.activeName1">
				<el-tab-pane label="基本信息" name="first"></el-tab-pane>
			</el-tabs>
			<el-form ref="dialogFormRef" :model="state.ruleForm" size="default" label-width="120px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="租户名" prop="name">
							<el-input v-model="state.ruleForm.name" placeholder="请输入租户名" clearable disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="联系人" prop="contactName">
							<el-input v-model="state.ruleForm.contactName" placeholder="请输入联系人" clearable disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="手机号" prop="contactMobile">
							<el-input v-model="state.ruleForm.contactMobile" placeholder="请输入手机号" clearable disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="绑定域名" prop="website">
							<el-input v-model="state.ruleForm.website" placeholder="请输入绑定域名" clearable disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账号数量" prop="accountCount">
							<el-input-number v-model="state.ruleForm.accountCount" :min="1" :max="10" disabled />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="租户状态" prop="status">
							<el-switch
								v-model="state.ruleForm.status"
								size="default"
								:active-value="0"
								:inactive-value="1"
								active-text="启用"
								inactive-text="禁用"
								inline-prompt
								style="--el-switch-on-color: #13ce66"
								disabled
							></el-switch>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-tabs v-model="state.activeName2">
				<el-tab-pane label="功能套餐包" name="second">
					<el-form-item v-if="!state.dialog.isDetail">
						<div class="btn3 ml10" @click="addPackageRow">
							<el-icon> <ele-CirclePlus /> </el-icon><span class="ml6">新增套餐包</span>
						</div>
					</el-form-item>
				</el-tab-pane>
			</el-tabs>
			<el-table
				ref="tableRef"
				:data="state.tablePackageData"
				row-key="id"
				border
				style="width: 100%"
				v-loading="state.tableLoading"
				highlight-current-row
				:cell-style="{ textAlign: 'center' }"
				:header-cell-style="{ background: '#1E4897', color: '#499AFD', textAlign: 'center' }"
			>
				<el-table-column show-overflow-tooltip label="序号" width="80" type="index" fixed />
				<el-table-column show-overflow-tooltip prop="packageId" label="功能套餐包">
					<template #default="{ row }">
						<el-select v-model="row.packageId" class="m-2" placeholder="请选择套餐包" :disabled="row.disabled">
							<el-option v-for="item in state.allPackageList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</template>
				</el-table-column>

				<el-table-column show-overflow-tooltip prop="expireTime" label="到期时间">
					<template #default="{ row }">
						<el-date-picker
							class="w100"
							v-model="row.expireTime"
							type="date"
							format="YYYY-MM-DD HH:mm:ss"
							value-format="YYYY-MM-DD HH:mm:ss"
							:default-time="new Date('1 00:00:00')"
							placeholder="请选择到期时间"
							:disabled="row.disabled"
						/>
					</template>
				</el-table-column>

				<!-- 操作按钮列表 -->
				<el-table-column fixed="right" label="操作" width="160" v-if="!state.dialog.isDetail">
					<template #default="{ row, $index }">
						<el-button v-if="row.disabled" size="small" link type="success" :disabled="!row.disabled" @click="openEditPackageRow(row)"
							>修改</el-button
						>
						<el-button v-if="!row.disabled" link type="danger" size="small" @click="deletePackageRow(row, $index)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-tabs v-model="state.activeName3" class="mt10" v-if="state.dialog.isDetail">
				<el-tab-pane label="租户权限套餐" name="third">
					<el-tree
						ref="treeRef"
						:data="state.allMenuData"
						:props="state.menuProps"
						node-key="id"
						:default-checked-keys="state.defaultChecked"
						:default-expanded-keys="state.defaultChecked"
						show-checkbox
						check-strictly
						class="menu-data-tree"
					/>
				</el-tab-pane>
			</el-tabs>

			<div class="flex row-center mt10 mb10">
				<div class="btn3" @click="onCancel">
					<el-icon> <ele-Close /> </el-icon><span class="ml6">取 消</span>
				</div>
				<div class="btn1 ml10" @click="onSubmit" v-if="!state.dialog.isDetail">
					<el-icon> <ele-Check /> </el-icon><span class="ml6">保 存</span>
				</div>
			</div>
		</el-dialog>
		<!-- 修改单个套餐包信息 -->
		<EditPackageDialog ref="editPackageDialogRef" @refresh="getTenantPackageInfo(state.ruleForm.id)" />
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { usePackageApi } from '/@/api/system/package/index';
import { ElNotification } from 'element-plus';
const EditPackageDialog = defineAsyncComponent(() => import('./editPackageDialog.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
// 定义变量内容
const dialogFormRef = ref();
const editPackageDialogRef = ref();
const state: any = reactive({
	activeName1: 'first',
	activeName2: 'second',
	activeName3: 'third',
	tenantPackage: [], // 租户已绑定的套餐包信息
	tablePackageData: [], // 套餐包表格绑定的数据
	allPackageList: [], // 所有套餐包列表
	ruleForm: {},
	dialog: {
		isShowDialog: false,
		isDetail: false,
	},
	menuProps: {
		children: 'childList',
		label: 'title',
		disabled: 'disabled',
	},
	allMenuData: [], // 所有菜单权限
	defaultChecked: [], // 默认选中的id集合
});

// 打开弹窗
const openDialog = (row: any, isDetail: boolean) => {
	state.dialog.isDetail = isDetail;
	state.ruleForm = {
		id: row.id,
		name: row.name, // 角色名称
		contactName: row.contactName, // 联系人
		contactMobile: row.contactMobile, // 联系手机 用于创建管理员账号
		website: row.website, // 绑定域名
		accountCount: row.accountCount, // 账号数量
		status: row.status, // 账号数量
	};
	getAllPackage();
	getTenantPackageInfo(row.id);
	state.dialog.isShowDialog = true;
};

// 获取所有套餐包
const getAllPackage = async () => {
	const { data } = await usePackageApi().pageModulePackage({
		pageNum: 1,
		pageSize: 100,
	});
	state.allPackageList = data.records;
};

// 查询租户生效套餐包和功能详情
const getTenantPackageInfo = async (id: string) => {
	const { data } = await usePackageApi().getTenantPackageInfo({ tenantId: id });
	state.tenantPackage = data.packages.map((item: any) => {
		return {
			name: item.name, // 套餐包名
			packageId: item.id, // 套餐包id
			tenantPackageId: item.tenantPackageId, // 开通套餐包的记录id
			expireTime: item.expireTime,
			status: item.status, // 套餐状态(0=正常 1=停用)
			disabled: true,
		};
	});
	state.tablePackageData = [...state.tenantPackage];
	state.allMenuData = [...data.menus];

	let tileData: any = [];
	function changMenuData(data: []) {
		data.forEach((item: any) => {
			item.disabled = 1;
			tileData.push(item);
			if (item.childList && item.childList.length > 0) {
				changMenuData(item.childList);
			}
		});
	}
	changMenuData(data.menus);

	state.defaultChecked = [];
	tileData.map((item: any) => {
		if (item.selected == 1) {
			state.defaultChecked.push(item.id);
		}
	});
};

// 新增一行
const addPackageRow = () => {
	state.tablePackageData.push({
		packageId: '',
		expireTime: '',
		disabled: false,
	});
};

// 删除一行
const deletePackageRow = (row: any, index: number) => {
	state.tablePackageData.splice(index, 1);
};

// 修改单行套餐包信息
const openEditPackageRow = (row: any) => {
	editPackageDialogRef.value.openDialog(row);
};

// 绑定套餐包-只能首次绑定
const bindPackage = async () => {
	// 过滤已绑定套餐包
	const filteredArr = state.tablePackageData.filter((item: any) => {
		return !state.tenantPackage.some((i: any) => i.packageId === item.packageId);
	});

	const data = await usePackageApi().bindPackage({
		tenantId: state.ruleForm.id,
		packages: filteredArr.map((item: any) => {
			return { packageId: item.packageId, expireTime: item.expireTime };
		}),
	});
	if (data.code == 200) {
		ElNotification({
			title: '提示',
			message: '绑定套餐包成功',
			position: 'top-right',
			type: 'success',
		});
		emit('refresh');
		closeDialog();
	}
};

// 提交
const onSubmit = () => {
	// 校验是否选择了套餐包
	if (state.tablePackageData.length == 0) {
		ElNotification({
			title: '提示',
			message: '校验失败,请添加套餐包',
			position: 'top-right',
			type: 'error',
		});
	} else {
		const isEmpty = state.tablePackageData.some((item: any) => item.packageId == '' || item.expireTime == '');
		isEmpty ? ElNotification({ title: '提示', message: '校验失败,请选择套餐包或到期时间', position: 'top-right', type: 'error' }) : bindPackage();
	}
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};

// 表单清空
const resetData = () => {
	dialogFormRef.value.resetFields();
	state.ruleForm = {
		id: '',
		name: '', // 租户名
		contactName: '', // 联系人
		contactMobile: '', // 联系手机 用于创建管理员账号
		website: '', // 绑定域名
		accountCount: 0, // 账号数量
		status: '', // 租户状态
	};
	state.tablePackageData = [];
	state.allMenuData = [];
	state.defaultChecked = [];
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss"></style>
